#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

#define PORT 8888
#define BUF_SIZE 1024

using namespace std;

void receive_messages(int sockfd) {
    char buf[BUF_SIZE];
    while (true) {
        int n = recv(sockfd, buf, BUF_SIZE - 1, 0);
        if (n <= 0) {
            cout << "\n[Disconnected from server]\n";
            exit(0);
        }
        buf[n] = '\0';
        cout << buf << flush;
    }
}

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }

    sockaddr_in serv_addr{};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connect");
        return 1;
    }

    string nickname;
    cout << "Enter your nickname: ";
    getline(cin, nickname);
    send(sockfd, nickname.c_str(), nickname.length(), 0);

    thread recv_thread(receive_messages, sockfd);

    while (true) {
        string msg;
        getline(cin, msg);
        if (msg.empty()) continue;
        msg += '\n';
        send(sockfd, msg.c_str(), msg.size(), 0);
    }

    close(sockfd);
    return 0;
}

